package com.itheima.controller;

import com.itheima.confirm.myConfirmCallback;
import com.itheima.confirm.myReturnsCallback;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private myConfirmCallback myConfirmCallback;

    @Autowired
    private myReturnsCallback myReturnsCallback;

    /**
     * 测试confirm机制回调函数功能
     *
     * @return
     */
    @GetMapping("/send1")
    public String send1() {
        //设置confirms
        rabbitTemplate.setConfirmCallback(myConfirmCallback);

        rabbitTemplate.convertAndSend("exchange_direct_demo01", "item.insert", "hello insert");
        return "Success";
    }

    /**
     * 测试Return机制回调函数功能
     *
     * @return
     */
    @GetMapping("/send2")
    public String send2() {
        //设置confirms
        rabbitTemplate.setReturnCallback(myReturnsCallback);

        rabbitTemplate.convertAndSend("exchange_direct_demo01", "item.insert", "hello insert");
        return "Success";
    }

    /**
     * 测试ack消费者确认功能
     *
     * @return
     */
    @GetMapping("/send3")
    public String send3() {
        //设置回调函数
        //发送消息
        rabbitTemplate.convertAndSend("exchange_direct_demo01", "item.insert", "hello insert");
        return "Success";
    }

    /**
     * 测试延迟队列功能
     *
     * @return
     */
    @GetMapping("/send4")
    public String send4() {
        //模拟下单
        System.out.println("下单成功...");
        //模拟减库存
        System.out.println("减库存成功...");

        System.out.println("下单的时间：" + new Date());

        //生产者 发送消息
        rabbitTemplate.convertAndSend("exchange_direct_demo01","item.insert",(Object) "延迟队列的消息：orderId的值:123456", new MessagePostProcessor() {
            //设置过期时间 设置消息的一些属性
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration("10000");//设置过期时间 单位是毫秒
                return message;
            }
        });
        return "Success";
    }
}
